package com.newdjk.newdoctor.ui;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;

import com.google.gson.Gson;
import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.dialog.CityChooseDialog;
import com.newdjk.newdoctor.entity.RenzhengInfoEntity;
import com.newdjk.newdoctor.entity.UploadImageEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Base64Util;
import com.newdjk.newdoctor.utils.DisplayUtil;
import com.newdjk.newdoctor.utils.GlideUtils;
import com.newdjk.newdoctor.utils.IDCard;
import com.newdjk.newdoctor.utils.LogUtils;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.MultiImageUploadView;
import com.newdjk.newdoctor.view.RoundImageUploadView;
import com.newdjk.okhttp.entity.BaseEntity;
import com.newdjk.okhttp.entity.RegisterEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class RenzhengActivity extends BasActivity {


    private static final String TAG = "RenzhengActivity";


    private final int IMAGE_REQUEST_CODE_XUKEZHENG = 2;
    private final int IMAGE_REQUEST_CODE_ZHIZHAO = 3;
    private final int IMAGE_REQUEST_CODE_IDCARD_FRONT = 4;
    private final int IMAGE_REQUEST_CODE_IDCARD_BACK = 5;
    private final int IMAGE_REQUEST_CODE_YILIAO_XUKEZHENG = 1;
    private final int IMAGE_REQUEST_CODE_GSP = 6;
    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.lv_result)
    LinearLayout lvResult;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_name)
    EditText tvName;
    @BindView(R.id.tv_xukezheng_title)
    TextView tvXukezhengTitle;
    @BindView(R.id.tv_zhengshu)
    EditText tvZhengshu;
    @BindView(R.id.tv_area_title)
    TextView tvAreaTitle;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_detail_address)
    EditText tvDetailAddress;
    @BindView(R.id.im_yiliao_xukezheng)
    RoundImageUploadView imYiliaoXukezheng;
    @BindView(R.id.lv_yiliao_xukezheng)
    LinearLayout lvYiliaoXukezheng;
    @BindView(R.id.im_xukezheng)
    RoundImageUploadView imXukezheng;
    @BindView(R.id.lv_yaodian_xukezheng)
    LinearLayout lvYaodianXukezheng;
    @BindView(R.id.tv_title_xukezheng)
    TextView tvTitleXukezheng;
    @BindView(R.id.im_zhizhao)
    RoundImageUploadView imZhizhao;
    @BindView(R.id.im_GSP)
    RoundImageUploadView imGSP;
    @BindView(R.id.lv_GSP_renzheng)
    LinearLayout lvGSPRenzheng;
    @BindView(R.id.tv_contract_name)
    EditText tvContractName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.im_shenfenzheng_front)
    RoundImageUploadView imShenfenzhengFront;
    @BindView(R.id.im_shenfenzheng_back)
    RoundImageUploadView imShenfenzhengBack;
    @BindView(R.id.tv_shenfenz)
    EditText tvShenfenz;
    @BindView(R.id.btn_submit)
    AppCompatButton btnSubmit;

    private String mProvinceName;
    private String mProvinceID;
    private String mcityName;
    private String mcityID;
    private String mAreaid;
    private String mAreaName;
    private String currentarea;
    private int mRelCompanyId;
    private int mRegType;
    Gson mGson = new Gson();
    private int mRelDrId;
    private int mAuditStatus;
    private int reletype;
    private RegisterEntity.ClinicAccreditationBean databean;
    private List<String> imYiliaoXukezhengPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> imXukezhengPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> imZhizhaoPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> imGSPPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> imShenfenzhengFrontPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> imShenfenzhengBackPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private int IMAGE_REQUEST_imShenfenzhengBack_CODE = 1;
    int width = 0;
    int imageWidth = 0;
    int imageheith = 0;

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }

    @Override
    protected String setTitle() {
        return "机构认证";
    }




    @Override
    protected void initView() {
        //  1诊所，2医生，3诊所并且是医生,4，药房  0啥都不是  诊所无申请处方
        reletype = MyApplication.DoctorInfoEntity.getRoleType();
        if (reletype == 1 || reletype == 2 || reletype == 3) {
            tvTitle.setText("机构名称");
            tvXukezhengTitle.setText("执业许可证编号");
            tvAreaTitle.setText("机构区域");
        } else {
            tvXukezhengTitle.setText("许可证编号");
            tvAreaTitle.setText("药店区域");
            lvGSPRenzheng.setVisibility(View.VISIBLE);
        }
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;         // 屏幕宽度（像素）
        imageWidth = Dp2Px(180);
        imageheith =Dp2Px(100);
        if (imageWidth==0){
            imageWidth=470;
        }
        if (imageheith==0){
            imageheith=300;
        }
        setUpimYiliaoXukezheng();
        setUpimXukezheng();
        setUpimZhizhao();
        setUpimGSP();
        setUpimShenfenzhengFront();
        setUpimShenfenzhengBack();

    }
    public int Dp2Px(float dp) {
        final float scale = RenzhengActivity.this.getResources().getDisplayMetrics().density; //当前屏幕密度因子
        return (int) (dp * scale + 0.5f);
    }
    private void startSelectImage(RoundImageUploadView view, int requestcode) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, requestcode);

    }


    private void setUpimShenfenzhengBack() {
        imShenfenzhengBack.setAddHandlerImage(R.drawable.image_add);
        imShenfenzhengBack.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return (int) (imageWidth*0.8);
            }

            @Override
            public int getHeight() {
                return (int) (imageheith*0.8);
            }
        });
        imShenfenzhengBack.setMax(1);
        imShenfenzhengBack.setNumCol(4);
        imShenfenzhengBack.setImgMargin(DisplayUtil.dp2px(this, 10));
        imShenfenzhengBack.setCloseHandlerImage(R.drawable.ic_delete_photo);
        imShenfenzhengBack.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG, parent.getFiles().get(position).getPath() + "" + position);
                ArrayList<String> list = new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(RenzhengActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position", position);
                startActivity(intent);
            }
        });
        imShenfenzhengBack.setPadding(0, 0, 0, 0);
        imShenfenzhengBack.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(imShenfenzhengBack, IMAGE_REQUEST_CODE_IDCARD_BACK);
            }
        });

        imShenfenzhengBack.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (imShenfenzhengBackPicList.size() > 0) {
                    imShenfenzhengBackPicList.remove(pos);
                }

            }
        });
    }

    private void setUpimShenfenzhengFront() {
        imShenfenzhengFront.setAddHandlerImage(R.drawable.image_add);
        imShenfenzhengFront.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return (int) (imageWidth*0.8);
            }

            @Override
            public int getHeight() {
                return (int) (imageheith*0.8);
            }
        });
        imShenfenzhengFront.setMax(1);
        imShenfenzhengFront.setNumCol(4);
        imShenfenzhengFront.setImgMargin(DisplayUtil.dp2px(this, 10));
        imShenfenzhengFront.setCloseHandlerImage(R.drawable.ic_delete_photo);
        imShenfenzhengFront.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG, parent.getFiles().get(position).getPath() + "" + position);
                ArrayList<String> list = new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(RenzhengActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position", position);
                startActivity(intent);
            }
        });
        imShenfenzhengFront.setPadding(0, 0, 0, 0);
        imShenfenzhengFront.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(imShenfenzhengFront, IMAGE_REQUEST_CODE_IDCARD_FRONT);
            }
        });

        imShenfenzhengFront.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (imShenfenzhengFrontPicList.size() > 0) {
                    imShenfenzhengFrontPicList.remove(pos);
                }

            }
        });
    }

    private void setUpimGSP() {
        imGSP.setAddHandlerImage(R.drawable.image_add);
        imGSP.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return imageWidth;
            }

            @Override
            public int getHeight() {
                return imageheith;
            }
        });
        imGSP.setMax(1);
        imGSP.setNumCol(4);
        imGSP.setImgMargin(DisplayUtil.dp2px(this, 10));
        imGSP.setCloseHandlerImage(R.drawable.ic_delete_photo);
        imGSP.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG, parent.getFiles().get(position).getPath() + "" + position);
                ArrayList<String> list = new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(RenzhengActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position", position);
                startActivity(intent);
            }
        });
        imGSP.setPadding(0, 0, 0, 0);
        imGSP.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(imGSP, IMAGE_REQUEST_CODE_GSP);
            }
        });

        imGSP.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (imZhizhaoPicList.size() > 0) {
                    imZhizhaoPicList.remove(pos);
                }

            }
        });
    }

    private void setUpimZhizhao() {
        imZhizhao.setAddHandlerImage(R.drawable.image_add);
        imZhizhao.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return imageWidth;
            }

            @Override
            public int getHeight() {
                return imageheith;
            }
        });
        imZhizhao.setMax(1);
        imZhizhao.setNumCol(4);
        imZhizhao.setImgMargin(DisplayUtil.dp2px(this, 10));
        imZhizhao.setCloseHandlerImage(R.drawable.ic_delete_photo);
        imZhizhao.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG, parent.getFiles().get(position).getPath() + "" + position);
                ArrayList<String> list = new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(RenzhengActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position", position);
                startActivity(intent);
            }
        });
        imZhizhao.setPadding(0, 0, 0, 0);
        imZhizhao.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(imZhizhao, IMAGE_REQUEST_CODE_ZHIZHAO);
            }
        });

        imZhizhao.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (imZhizhaoPicList.size() > 0) {
                    imZhizhaoPicList.remove(pos);
                }

            }
        });
    }

    private void setUpimXukezheng() {
        imXukezheng.setAddHandlerImage(R.drawable.image_add);
        imXukezheng.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return imageWidth;
            }

            @Override
            public int getHeight() {
                return imageheith;
            }
        });
        imXukezheng.setMax(1);
        imXukezheng.setNumCol(4);
        imXukezheng.setImgMargin(DisplayUtil.dp2px(this, 10));
        imXukezheng.setCloseHandlerImage(R.drawable.ic_delete_photo);
        imXukezheng.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG, parent.getFiles().get(position).getPath() + "" + position);
                ArrayList<String> list = new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(RenzhengActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position", position);
                startActivity(intent);
            }
        });
        imXukezheng.setPadding(0, 0, 0, 0);
        imXukezheng.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(imXukezheng, IMAGE_REQUEST_CODE_XUKEZHENG);
            }
        });

        imXukezheng.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (imXukezhengPicList.size() > 0) {
                    imXukezhengPicList.remove(pos);
                }

            }
        });
    }

    private void setUpimYiliaoXukezheng() {
        imYiliaoXukezheng.setAddHandlerImage(R.drawable.image_add);
        imYiliaoXukezheng.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return imageWidth;
            }

            @Override
            public int getHeight() {
                return imageheith;
            }
        });
        imYiliaoXukezheng.setMax(1);
        imYiliaoXukezheng.setNumCol(4);
        imYiliaoXukezheng.setImgMargin(DisplayUtil.dp2px(this, 10));
        imYiliaoXukezheng.setCloseHandlerImage(R.drawable.ic_delete_photo);
        imYiliaoXukezheng.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG, parent.getFiles().get(position).getPath() + "" + position);
                ArrayList<String> list = new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(RenzhengActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position", position);
                startActivity(intent);
            }
        });
        imYiliaoXukezheng.setPadding(0, 0, 0, 0);
        imYiliaoXukezheng.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(imYiliaoXukezheng, IMAGE_REQUEST_CODE_YILIAO_XUKEZHENG);
            }
        });

        imShenfenzhengBack.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (imYiliaoXukezhengPicList.size() > 0) {
                    imYiliaoXukezhengPicList.remove(pos);
                }

            }
        });
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_renzheng;
    }

    @Override
    protected void initListener() {


        if (null != MyApplication.medicationCompanyEntity) {
            if (MyApplication.medicationCompanyEntity.getCheckStatus() ==2) {
                btnSubmit.setVisibility(View.GONE);
            }

        }


        NetServices.Factory.getService().QueryClinicAccreditationInfo(
                MyApplication.LoginEntity.getUser().getDoctorId() + ""
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<RegisterEntity>(RenzhengActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity<RegisterEntity> t) throws Exception {
                        Log.d(TAG, t.getData().toString());
                        databean = t.getData().getClinicAccreditation();
                        mRegType = databean.getRegType();//注册机构类型。0诊所；1药房
                        if (mRegType == 0) {
                            lvYaodianXukezheng.setVisibility(View.GONE);
                            lvYiliaoXukezheng.setVisibility(View.VISIBLE);
                            tvTitleXukezheng.setText("诊所营业执照复印件（非盈利机构请上传执业证）");
                        } else {
                            lvYaodianXukezheng.setVisibility(View.VISIBLE);
                            lvYiliaoXukezheng.setVisibility(View.GONE);
                            tvTitleXukezheng.setText("药店经营执照");
                        }

                        mProvinceName = databean.getProvinceName();
                        mProvinceID = databean.getProvinceId();

                        mcityName = databean.getCityName();
                        mcityID = databean.getCityId();
                        mAreaName = databean.getAreaName();
                        mAreaid = databean.getAreaId();

                        mRelDrId = databean.getRelDrId();


                        mRelCompanyId = t.getData().getClinicAccreditation().getRelCompanyId();
                        tvName.setText(t.getData().getClinicAccreditation().getCompanyName());
                        tvLocation.setText((TextUtils.isEmpty(mProvinceName) ? "" : mProvinceName) + (TextUtils.isEmpty(mcityName) ? "" : mcityName) + (TextUtils.isEmpty(mAreaName) ? "" : mAreaName));
                        tvMobile.setText(t.getData().getClinicAccreditation().getMobile());
                        tvZhengshu.setText(TextUtils.isEmpty(databean.getPracticeLicenseNumber()) ? "" : databean.getPracticeLicenseNumber());
                        tvDetailAddress.setText(TextUtils.isEmpty(databean.getAddress()) ? "" : databean.getAddress());
                        tvContractName.setText(TextUtils.isEmpty(databean.getLinkMan()) ? "" : databean.getLinkMan());
                        tvMobile.setText(TextUtils.isEmpty(databean.getMobile()) ? "" : databean.getMobile());
                        tvShenfenz.setText(TextUtils.isEmpty(databean.getCredNo()) ? "" : databean.getCredNo());

                        List<RegisterEntity.ClinicAccreditationImgsBean> listimg = t.getData().getClinicAccreditationImgs();
                        mAuditStatus = databean.getAuditStatus();//审核状态。0未审核(审核中)；1审核通过；2审核未通过(驳回)
                        if (mAuditStatus == 1) {
                            lvResult.setVisibility(View.GONE); //是否显示认证状态
                        } else if (mAuditStatus == 0) {
                            if (listimg != null) {
                                if (listimg.size() > 0) {  //如果审核状态等于0 并且没有上传过图片就不显示认证状态
                                    lvResult.setVisibility(View.VISIBLE);
                                } else {
                                    lvResult.setVisibility(View.GONE);
                                }
                            } else {
                                lvResult.setVisibility(View.GONE);
                            }
                        } else {
                            lvResult.setVisibility(View.VISIBLE);
                        }
                        switch (mAuditStatus) {
                            case 0:
                                tvResult.setText("认证中");
                                break;
                            case 1:
                                tvResult.setText("审核通过");
                                break;
                            case 2:
                                tvResult.setText("审核不通过");
                                break;
                        }
                        if (listimg != null) {
                            if (listimg.size() > 0) {
                                for (int i = 0; i < listimg.size(); i++) {
                                    int type = listimg.get(i).getImgType();
                                    //图片类型(1：执业许可证，2：营业执照，3：身份证正面，4：身份证反面，5：药品经营许可证，6：GSP认证)
                                    switch (type) {
                                        case 0:

                                            break;
                                        case 1:
                                            imYiliaoXukezheng.setTag(listimg.get(i).getPicturePath());
                                            imYiliaoXukezheng.addFile(new File(listimg.get(i).getPicturePath()));
                                            break;
                                        case 2:
                                            imZhizhao.setTag(listimg.get(i).getPicturePath());
                                            imZhizhao.addFile(new File(listimg.get(i).getPicturePath()));
                                            break;
                                        case 3:
                                            imShenfenzhengFront.setTag(listimg.get(i).getPicturePath());
                                            imShenfenzhengFront.addFile(new File(listimg.get(i).getPicturePath()));
                                            break;
                                        case 4:
                                            imShenfenzhengBack.setTag(listimg.get(i).getPicturePath());
                                            imShenfenzhengBack.addFile(new File(listimg.get(i).getPicturePath()));
                                            break;
                                        case 5:
                                            imXukezheng.setTag(listimg.get(i).getPicturePath());
                                            imXukezheng.addFile(new File(listimg.get(i).getPicturePath()));
                                            break;
                                        case 6:
                                            imGSP.setTag(listimg.get(i).getPicturePath());
                                            imGSP.addFile(new File(listimg.get(i).getPicturePath()));
                                            break;
                                    }

                                }
                            }
                        }

                    }

                });


        imXukezheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE_XUKEZHENG);
            }
        });

        imZhizhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE_ZHIZHAO);
            }
        });

        imShenfenzhengFront.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE_IDCARD_FRONT);
            }
        });
        imShenfenzhengBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE_IDCARD_BACK);
            }
        });

        imYiliaoXukezheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE_YILIAO_XUKEZHENG);
            }
        });

        imGSP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE_GSP);
            }
        });

        //选择地址
        tvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityChooseDialog.getInstance().showBottomSexDialog(RenzhengActivity.this, "", new CityChooseDialog.CitySelectListener() {

                    @Override
                    public void citySelectListener(String provinceName, String cityName, String areaName, String path) {
                        String[] list = path.split(",");
                        if (list.length == 5) {
                            mProvinceName = provinceName;
                            mProvinceID = list[2] + "";
                            mcityName = cityName;
                            mcityID = list[3] + "";
                            mAreaName = areaName;
                            mAreaid = list[4] + "";
                            currentarea = provinceName + cityName + areaName;
                            tvLocation.setText(currentarea);
                        } else {
                            mProvinceName = provinceName;
                            mProvinceID = list[2] + "";
                            mcityName = cityName;
                            mcityID = list[3] + "";
                            mAreaName = areaName;
                            mAreaid = "0";
                            currentarea = provinceName + cityName + areaName;
                            tvLocation.setText(currentarea);
                        }

                    }
                });
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tvName.getText().toString())) {
                    if (reletype == 1 || reletype == 2 || reletype == 3) {
                        ToastUtil.setToast("机构名称不能为空");
                    } else {
                        ToastUtil.setToast("药店名称不能为空");
                    }

                    return;
                }
//                if (TextUtils.isEmpty(tvZhengshu.getText().toString())) {
//                    ToastUtil.setToast("许可证编号不能为空");
//                    return;
//                }
                if (TextUtils.isEmpty(tvLocation.getText().toString())) {

                    if (reletype == 1 || reletype == 2 || reletype == 3) {
                        ToastUtil.setToast("机构区域不能为空");
                    } else {
                        ToastUtil.setToast("药店区域不能为空");
                    }
                    return;
                }
                if (TextUtils.isEmpty(tvDetailAddress.getText().toString())) {
                    ToastUtil.setToast("详细地址不能为空");
                    return;
                }
                if (reletype == 1 || reletype == 2 || reletype == 3) {
                    if (imYiliaoXukezheng.getTag() == null) {
                        ToastUtil.setToast("请上传医疗机构执业许可证");
                        return;
                    }
                    if (imZhizhao.getTag() == null) {
                        ToastUtil.setToast("请上传诊所营业执照复印件");
                        return;
                    }
                } else {
                    if (imXukezheng.getTag() == null) {
                        ToastUtil.setToast("请上传药店经营许可证");
                        return;
                    }
                    if (imZhizhao.getTag() == null) {
                        ToastUtil.setToast("请上传药店经营执照");
                        return;
                    }
                }

                if (reletype == 4) {
                    if (imGSP.getTag() == null) {
                        ToastUtil.setToast("请上传GSP认证");
                        return;
                    }
                }

                if (TextUtils.isEmpty(tvContractName.getText().toString())) {
                    ToastUtil.setToast("联系人姓名不能为空");
                    return;
                }
                if (imShenfenzhengFront.getTag() == null) {
                    ToastUtil.setToast("请上传身份证正面");
                    return;
                }
                if (!TextUtils.isEmpty(tvShenfenz.getText().toString())) {
                    if (!IDCard.validate_effective(tvShenfenz.getText().toString())) {
                        ToastUtil.setToast("请输入正确的身份证号码");
                        return;
                    }
                }


                if (imShenfenzhengBack.getTag() == null) {
                    ToastUtil.setToast("请上传身份证反面");
                    return;
                }
//                if (TextUtils.isEmpty(tvShenfenz.getText().toString())) {
//                    ToastUtil.setToast("身份证号码不能为空");
//                    return;
//                }
//                if (!IDCard.validate_effective(tvShenfenz.getText().toString())) {
//                    ToastUtil.setToast("请输入正确的身份证号码");
//                    return;
//                }
                //  ToastUtil.setToast("提交成功");
                //图片类型(1：执业许可证，2：营业执照，3：身份证正面，4：身份证反面，5：药品经营许可证，6：GSP认证)

                RenzhengInfoEntity renzhengInfoEntity = new RenzhengInfoEntity();
                renzhengInfoEntity.setPracticeLicenseNumber(TextUtils.isEmpty(tvZhengshu.getText().toString()) ? "" : tvZhengshu.getText().toString() + ""); //许可证编号
                renzhengInfoEntity.setCompanyName(tvName.getText().toString()); //药店名称
                renzhengInfoEntity.setAddress(tvDetailAddress.getText().toString()); //详细地址
                renzhengInfoEntity.setRelCompanyId(mRelCompanyId);//关联医药集团id。
                renzhengInfoEntity.setLinkMan(tvContractName.getText().toString());//联系人姓名
                renzhengInfoEntity.setMobile(tvMobile.getText().toString());//电话
                renzhengInfoEntity.setCredNo(TextUtils.isEmpty(tvShenfenz.getText().toString()) ? "" : tvShenfenz.getText().toString());//身份证
                renzhengInfoEntity.setProvinceId(mProvinceID + "");
                renzhengInfoEntity.setProvinceName(mProvinceName + "");
                if (databean != null) {
                    renzhengInfoEntity.setClinicAccreditationId(databean.getClinicAccreditationId() + "");
                }
                renzhengInfoEntity.setAreaId(mAreaid + "");
                renzhengInfoEntity.setAreaName(mAreaName + "");
                renzhengInfoEntity.setCityId(mcityID + "");
                renzhengInfoEntity.setCityName(mcityName);
                renzhengInfoEntity.setRelDrId(mRelDrId);
                renzhengInfoEntity.setRegType(mRegType);
                List<RenzhengInfoEntity.ClinicAccreditationImgsBean> list = new ArrayList<>(); //图片类型(1：执业许可证，2：营业执照，3：身份证正面，4：身份证反面，5：药品经营许可证，6：GSP认证)


                if (mRegType == 0) {
                    RenzhengInfoEntity.ClinicAccreditationImgsBean beanyiliaoxukezheng = new RenzhengInfoEntity.ClinicAccreditationImgsBean();
                    beanyiliaoxukezheng.setImgType(1);
                    beanyiliaoxukezheng.setPicturePath(imYiliaoXukezheng.getTag().toString());
                    list.add(beanyiliaoxukezheng);
                } else {
                    RenzhengInfoEntity.ClinicAccreditationImgsBean beanxukezheng = new RenzhengInfoEntity.ClinicAccreditationImgsBean();
                    beanxukezheng.setImgType(5);
                    beanxukezheng.setPicturePath(imXukezheng.getTag().toString());
                    list.add(beanxukezheng);
                }

                if (reletype == 4) {
                    RenzhengInfoEntity.ClinicAccreditationImgsBean GSPrenzheng = new RenzhengInfoEntity.ClinicAccreditationImgsBean();
                    GSPrenzheng.setImgType(6);
                    GSPrenzheng.setPicturePath(imGSP.getTag().toString());
                    list.add(GSPrenzheng);
                }

                RenzhengInfoEntity.ClinicAccreditationImgsBean beanzhizhao = new RenzhengInfoEntity.ClinicAccreditationImgsBean();
                beanzhizhao.setImgType(2);
                beanzhizhao.setPicturePath(imZhizhao.getTag().toString());
                list.add(beanzhizhao);

                RenzhengInfoEntity.ClinicAccreditationImgsBean beancardFront = new RenzhengInfoEntity.ClinicAccreditationImgsBean();
                beancardFront.setImgType(3);
                beancardFront.setPicturePath(imShenfenzhengFront.getTag().toString());
                list.add(beancardFront);

                RenzhengInfoEntity.ClinicAccreditationImgsBean beancardBack = new RenzhengInfoEntity.ClinicAccreditationImgsBean();
                beancardBack.setImgType(4);
                beancardBack.setPicturePath(imShenfenzhengBack.getTag().toString());
                list.add(beancardBack);


                renzhengInfoEntity.setClinicAccreditationImgs(list);
                String json = mGson.toJson(renzhengInfoEntity);
                LogUtils.d(TAG, json);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
                NetServices.Factory.getService().SaveClinicAccreditation(
                        body
                ).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseComPleteObserver(RenzhengActivity.this) {
                            @Override
                            protected void onSuccees(BaseEntity t) throws Exception {
                                Log.d(TAG, t.getData().toString());
                                ToastUtil.setToast("提交成功");
                                finish();
                            }

                        });

            }
        });
    }


    @Override
    protected void initData() {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String path = "";
        if (resultCode == RESULT_OK) {
            try {
                Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = RenzhengActivity.this.getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                path = cursor.getString(columnIndex);  //获取照片路径

                //String compresspath = ImageUtil.compressImage(path);
                // sendPictureMessage(compresspath);

                cursor.close();
            } catch (Exception e) {
                // TODO Auto-generatedcatch block
                e.printStackTrace();
                return;
            }
        }
        switch (requestCode) {
            case IMAGE_REQUEST_CODE_XUKEZHENG:
                stringToBase64(path, imXukezheng);
                break;
            case IMAGE_REQUEST_CODE_ZHIZHAO:

                stringToBase64(path, imZhizhao);
                break;
            case IMAGE_REQUEST_CODE_IDCARD_FRONT:
                stringToBase64(path, imShenfenzhengFront);

                break;
            case IMAGE_REQUEST_CODE_IDCARD_BACK:

                stringToBase64(path, imShenfenzhengBack);
                break;
            case IMAGE_REQUEST_CODE_YILIAO_XUKEZHENG:

                stringToBase64(path, imYiliaoXukezheng);
                break;
            case IMAGE_REQUEST_CODE_GSP:

                stringToBase64(path, imGSP);
                break;
        }

    }

    public void compressImage(String filePath, final ObservableEmitter<String> emitter) {
        File oldFile = new File(filePath);
        Log.d("图片压缩", "之前" + oldFile.length());
        Luban.with(RenzhengActivity.this)
                .load(filePath)
                .ignoreBy(100)
                .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        Log.d(TAG, Thread.currentThread() + "" + file.getAbsolutePath());
                        Log.d("图片压缩", "之后" + file.length());
                        emitter.onNext(Base64Util.imageToBase64(file.getAbsolutePath()));


                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();

    }


    private void stringToBase64(final String path, final RoundImageUploadView imageView) {
        //   Base64Util.imageToBase64(path);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                compressImage(path, emitter);
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "onNext" + s);
                uploadImge(s, path, imageView);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void uploadImge(String s, final String path, RoundImageUploadView imageView) {

        NetServices.Factory.getService().UploadImage(
                s + ""
                , "3"
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<UploadImageEntity>(RenzhengActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity<UploadImageEntity> t) throws Exception {
                        Log.d(TAG, t.getData().toString());
                        imageView.addFile(new File(path));
                        imageView.setTag(t.getData().getDisplayPath());
                    }

                });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
